//
//  QDUserCenterTableViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/22.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

/// 个人中心界面
final class QDUserCenterTableViewController: NWTableViewController,QDUCInfoHeaderViewDelegate {

    /// 放置个人信息的headerView
    var headerView: QDUCInfoHeaderView?
    
    /// 数据源
    let titles = [["在线购票","支付管理","乘车记录","开具发票"],
                  ["帮助与客服","乘客服务","产品意见反馈"],
                  ["我的收藏"]]
    
    let imageNames = [["uc_icon_goupiao","uc_icon_zhifu","uc_icon_chengche","uc_icon_fapiao"],
                      ["uc_icon_kefu","uc_icon_chengkefuwu","uc_icon_feedback"],
                      ["uc_icon_collect"]]
    
    /// 附小标题
    var subtitles = [["","",""],["","","",""],["",""]]
    
    /// init数据
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        
        headerRefreshEnable = false
        footerRefreshEnable = false
        tableView.rowHeight = 56
    }
    
    /// 注册
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDUCTitleTableViewCell.self, forCellReuseIdentifier: "UCCell")
        tableView.register(QDUCLineSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: "UCLine")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let allSpace = hasPhoneHeader() ? 40 : 0
        
        //TODO: 装载tableHeaderView
        let headerView = QDUCInfoHeaderView(frame: CGRect(origin: .zero, size: CGSize(width: ritl_width, height: CGFloat(104 + allSpace)/*169  隐藏金融*/)))
        headerView.backgroundColor = .white
        headerView.delegate = self
        self.headerView = headerView
        self.headerView?.updateInfoStatus(isLogin: QDUserStatus.isLogin)
        tableView.tableHeaderView = headerView
        
        //设置
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: "uc_setting".namedImage?.ritl_renderOrigin, style: .done, target: self, action: #selector(pushToSettingViewController))
        
        //接收登陆通知
        NotificationCenter.default.addObserver(self, selector: #selector(catchLoginCompleteNotification), name: QDLoginCompleteNotificationName, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(catchLogoutCompleteNotification), name: QDLogoutCompleteNotificationName, object: nil)

        
        NotificationCenter.default.addObserver(self, selector: #selector(changedUserInformation), name: QDUserInfoStatusDidChangedNotificationName, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(changedUserInformation), name: QDPayTypeStatusDidChangedNotificationName, object: nil)
    }
    
    
    /// 个人信息发生变化
    @objc func changedUserInformation(){
        headerView?.updateInfoStatus(isLogin: true)
        tableView.reloadData()
    }
    
    
    /// 弹出我的信息界面
    @objc func pushtToMyInfoViewController(){
        //如果没有登陆
        if !QDUserStatus.isLogin { return; }
        router(platform: .myInfo)
    }
    
    
    /// 登陆完成
    @objc func catchLoginCompleteNotification(){
        headerView?.updateInfoStatus(isLogin: true)
        //刷新
        tableView.reloadData()
    }
    
    /// 退出登陆或者失效
    @objc func catchLogoutCompleteNotification(){
        headerView?.updateInfoStatus(isLogin: false)
        tableView.reloadData()
    }
    
    
    // MARK: NavigationBar
    override var nav_barShadowHidden: Bool { return true }
    
    
    // MARK: UITableViewDataSource
    override func numberOfSections(in tableView: UITableView) -> Int {
        return titles.count
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titles[section].count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "UCCell", for: indexPath)
        
        if let titleCell = cell as? QDUCTitleTableViewCell {
            titleCell.titleLabel.text = titles[indexPath.section][indexPath.row]
            titleCell.imageView.image = imageNames[indexPath.section][indexPath.row].namedImage
            
            let title = titles[indexPath.section][indexPath.row]
            
            if title == "在线购票" {
                titleCell.subtitleLabel.text = subtitles[indexPath.section][indexPath.row]
                
            }else if title == "支付管理" {
                print("列表 = \(QDUserInfoModel.share.currentChannel)")
                titleCell.subtitleLabel.text = QDUserStatus.isLogin ? QDUserInfoModel.share.currentChannel : nil
            }
        }
        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        // 只有第二组上方模拟分割线
        return [1,2].contains(section) ? tableView .dequeueReusableHeaderFooterView(withIdentifier: "UCLine") : nil
    }
    
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        // 只有第二组上方模拟分割线
        return [1,2].contains(section) ? 5.5 : CGFloat.leastNormalMagnitude
    }
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        //获得title
        let title = titles[indexPath.section][indexPath.row]
        let shouldLogin = ["在线购票","支付管理","乘车记录","产品意见反馈","我的收藏","开具发票"].contains(title)
        
        /// 支付管理
        func payManagerDidTap(){
            // 获得key
            let platformKey: UIViewController.PlatformKey = QDUserInfoModel.share.currentChannel.isEmpty ? .payTypeList : .payManager
            //进行跳转
            router(platform: platformKey)
        }
        
        switch title {
        case "在线购票": router(platform: .metroTicket(start: nil, end: nil)); QDUMEventManager.event(event: .buyTicket)
        case "支付管理": payManagerDidTap()
        case "乘车记录": router(platform: .record)
        case "乘客服务": router(platform: .userService); QDUMEventManager.event(event: .userService)
        case "我的收藏": router(platform: .myCollect)
        case "开具发票": router(platform: .bill)
        case "帮助与客服": router(platform: .support); QDUMEventManager.event(event: .commonQuestion)
        case "产品意见反馈": router(platform: .feed(type: .questionForApp))
        default: return
        }
        
        
        
        /// 收藏的控制器
//        func collectionViewController() -> QDMyCollectListViewController {
//
//            let collectViewController = QDMyCollectListViewController()
//            collectViewController.url = collectListUrl
//            collectViewController.title = "我的收藏"
//            collectViewController.hidesBottomBarWhenPushed = true
//
//            return collectViewController
//        }
//

//        var viewController: UIViewController? = nil
//
//        switch title {
//        case "在线购票": viewController = QDMetroTicketViewController(); QDUMEventManager.event(event: .buyTicket)
//        case "支付管理": viewController = nil
//        case "乘车记录": viewController = QDRecordIndexViewController()
//        case "乘客服务": viewController = QDUserServiceViewController(); QDUMEventManager.event(event: .userService)
//        case "我的收藏": /*viewController = collectionViewController()*/router(platform: .myCollect)
//        case "帮助与客服": viewController = QDSupportViewControler(); QDUMEventManager.event(event: .commonQuestion)
//        case "产品意见反馈": viewController = QDQuestionFeedViewController(type: .questionForApp)
//        default: viewController = UIViewController()
//        }
//
        
//        if shouldLogin {// 需要登录
//            checkLogin {
//                if title == "支付管理" { //如果没有支付方式，则跳入绑定支付方式界面
//                    viewController = QDUserInfoModel.share.currentChannel.isEmpty ? QDPayTypeViewController() : QDPayManagerViewController()
//                }
//
//                self.ritl_topNavigationPush(viewController!, animated: true);
//            }; return
//        }
//
//        ritl_topNavigationPush(viewController!, animated: true);
    }
    
    
    //MARK: Setting
    @objc func pushToSettingViewController(){
        router(platform: .setting)
    }
}

